//
//  oldNetWork.m
//  laonianbang
//
//  Created by 勇拓 李 on 17/10/9.
//  Copyright © 2017年 zaiyou. All rights reserved.
//

#import "oldNetWork.h"
#import "oldTools.h"
#import "oldEncrypt.h"
#import "QNuploader.h"

#define RET_OK                  0x0
#define RET_SERVER_SUCC         200
#define RET_SERVER_FAIL_412     412
#define RET_SERVER_FAIL         0X1

NSInteger const SXTokenError = 403;//token错误
NSInteger const SXTokenOverdue = 403;//token过期
NSInteger const Request_OK = 200;//正确

NSString * const SXTokenKey = @"SXTokenKey";

@implementation oldNetWork
{
    SXNetLoginState loginState;
    SXTokenUpdatingState tokenUpdatingState;
    
}

@synthesize token = _token;

+ ( instancetype ) shareInstance
{
    static oldNetWork * instance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once( &onceToken, ^
                  {
                      instance = [self new];
                  });
    return instance;
}

- ( id ) init
{
    if( self = [super init] )
    {
        loginState = UnLogined;//默认设置为未登录状态
        tokenUpdatingState = Updated;
        
        _manager = [[AFHTTPSessionManager alloc] init];
        AFHTTPResponseSerializer * response = [AFHTTPResponseSerializer serializer];
        _manager.responseSerializer = response;
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        
        [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        [self setAFHTTPSessionManagerToken:self.token];//初始化 manager
    }
    return self;
}

- ( void ) httpRequestWithGet : ( NSString * ) url
                       params : ( NSDictionary * ) params
                      success : ( SuccessBlock ) successBlock
                        error : ( ErrorBlock ) errorBlock
{
    WeakSelf
    
    [self.manager GET:url parameters:[self signByDes:params] progress:nil success:^(NSURLSessionTask *task, id responseObject)
     {
         NSHTTPURLResponse * response = (NSHTTPURLResponse *)task.response;
         
         //判断token是否过期
         if (response.statusCode == RET_SERVER_SUCC && responseObject != nil) {
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
             
             if([dic[@"code"] integerValue] == SXTokenOverdue||[dic[@"code"] integerValue] == SXTokenError)
             {
                 [weakSelf tokenError:@"请重新登录"];
             }
             else if([dic[@"code"] integerValue] == Request_OK)
             {
                 successBlock( dic[@"data"] );
             }
             else
             {
                 errorBlock(dic[@"errorMsg"]);
             }
         }
         else
         {
             errorBlock(nil);
         }
     }
               failure:^(NSURLSessionTask *task, NSError *error)
     {
         if(loginState != Logining)
         {
             errorBlock( @"网络故障" );
         }
     }];
}

- ( void ) httpRequestWithPostPut : ( NSString * ) url
                           params : ( NSDictionary * ) params
                          success : ( SuccessBlock ) successBlock
                            error : ( ErrorBlock ) errorBlock
{
    WeakSelf
    
    [self.manager POST:url parameters:[self signByDes:params] progress:nil success:^(NSURLSessionTask *task, id responseObject)
     {
         NSHTTPURLResponse * response = (NSHTTPURLResponse *)task.response;
         
         //判断token是否过期
         if (response.statusCode == RET_SERVER_SUCC && responseObject != nil) {
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
             
             if([dic[@"code"] integerValue] == SXTokenOverdue||[dic[@"code"] integerValue] == SXTokenError)
             {
                 [weakSelf tokenError:@"请重新登录"];
             }
             else if([dic[@"code"] integerValue] == Request_OK)
             {
                 successBlock( dic[@"data"] );
             }
             else
             {
                 errorBlock(dic[@"errorMsg"]);
             }
         }
         else
         {
             errorBlock(nil);
         }
     }
              failure:^(NSURLSessionTask *task, NSError *error)
     {
         if(loginState != Logining)
         {
             errorBlock( @"网络故障" );
         }
     }];
}

- (void)httpRequestWithGetHaveCache:(NSString *)url ifneedCache:(BOOL)ifneed params:(NSDictionary *)params premethod:(void (^)(NSDictionary *))premethod success:( SuccessBlock )successBlock error:(ErrorBlock) errorBlock
{
    if (ifneed) {
        NSString *user_cacheName = [oldTools getUserCacheName];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:user_cacheName]) {
            NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:user_cacheName];
            if (dic[url]) {
                premethod(dic[url]);
            }
        }
    }
    
    [self httpRequestWithGet:url params:[self signByDes:params] success:^(NSDictionary *response) {
        if (ifneed && [response[ @"success" ] boolValue]) {
            NSString *user_cacheName = [oldTools getUserCacheName];
            NSMutableDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:user_cacheName];
            if (!dic) {
                dic = [NSMutableDictionary dictionary];
            }
            [dic setObject:response forKey:url];
            [[NSUserDefaults standardUserDefaults] setObject:dic forKey:user_cacheName];
        }
        successBlock(response);
    } error:errorBlock];
}

- (void)httpRequestWithPostHaveCache:(NSString *)url ifneedCache:(BOOL)ifneed params:(NSDictionary *)params premethod:(void (^)(NSDictionary *))premethod success:( SuccessBlock )successBlock error:(ErrorBlock) errorBlock
{
    if (ifneed)
    {
        NSString *user_cacheName = [oldTools getUserCacheName];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:user_cacheName]) {
            NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:user_cacheName];
            if (dic[url]) {
                premethod(dic[url]);
            }
        }
    }
    
    [self httpRequestWithPostPut:url params:[self signByDes:params] success:^(NSDictionary *response) {
        if (ifneed && [response[ @"success" ] boolValue]) {
            NSString *user_cacheName = [oldTools getUserCacheName];
            NSMutableDictionary *dic = [[[NSUserDefaults standardUserDefaults] objectForKey:user_cacheName] mutableCopy];
            if (!dic) {
                dic = [NSMutableDictionary dictionary];
            }
            [dic setObject:response forKey:url];
            [[NSUserDefaults standardUserDefaults] setObject:dic forKey:user_cacheName];
        }
        successBlock(response);
    } error:errorBlock];
}

#pragma mark - 文件相关
- (void)downloadFile:(NSString *)url filePath:(NSString *)filePath block:(DownBlock)block
{
    /* 下载地址 */
    NSURL *nsurl = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:nsurl];
    
//    /* 下载路径 */
//    NSString *path = [NSHomeDirectory() stringByAppendingString:@"Documents"];
//    NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];
    
    /* 开始请求下载 */
    NSURLSessionDownloadTask *downloadTask = [_manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        /* 设定下载到的位置 */
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        block(filePath.absoluteString);
        NSLog(@"下载完成");
        
    }];
    [downloadTask resume];
}

#pragma mark - token相关
- (void)setAFHTTPSessionManagerToken:(NSString *)token
{
    if (token) {
        loginState = Logined;
        [_manager.requestSerializer setValue:token forHTTPHeaderField:@"TOKEN"];
    }
}

//token错误或者过期
- (void)tokenError:(NSString *)errorCode
{
    if (loginState == Logined) {
        loginState = Logining;//改为登陆中状态
        
        self.token = nil;
        tokenUpdatingState = Updated;
        if ( [self.delegate respondsToSelector:@selector(gotoLoginViewController:)] ) {
            [self.delegate gotoLoginViewController:errorCode];
        }
        else{
            loginState = Logined;
        }
    }
}

#pragma mark - 加密
- (NSDictionary *)signByDes:(NSDictionary *)params
{
    NSMutableDictionary *dic = [params mutableCopy];
    
    if (!dic) {
        dic = [NSMutableDictionary dictionary];
    }
    
    [dic setObject:APPNAME forKey:@"appName"];
    
    NSString *str = [oldEncrypt encryptByDes:dic];
    
    [dic setObject:str forKey:@"sign"];
    
    return [dic copy];
}

#pragma mark - 部分工具类方法
//获取token的方法
- (NSString *)token
{
    return _token ? _token : [[NSUserDefaults standardUserDefaults] objectForKey:SXTokenKey];
}

- (void)setToken:(NSString *)token
{
    _token = token;
    if(token)
    {
        loginState = Logined;//设置了token后改为登陆状态
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:token forKey:SXTokenKey];
    }
    else
    {
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        [defaults removeObjectForKey:SXTokenKey];
    }
}

- (void)clearToken
{
    self.token = nil;
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:SXTokenKey];
}

@end
